package cn.edu.ctbu.yrx.api;


import cn.edu.ctbu.yrx.constant.REnum;
import cn.edu.ctbu.yrx.dao.TeacherRepository;
import cn.edu.ctbu.yrx.entity.CourseScore;
import cn.edu.ctbu.yrx.entity.Student;
import cn.edu.ctbu.yrx.entity.Teacher;
import cn.edu.ctbu.yrx.rexception.RException;
import cn.edu.ctbu.yrx.service.CourseScoreService;
import cn.edu.ctbu.yrx.service.TeacherService;
import cn.edu.ctbu.yrx.util.RUtil;
import cn.edu.ctbu.yrx.vo.QueryObj;
import cn.edu.ctbu.yrx.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/admin/teacher")
public class TeacherApiController {

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private CourseScoreService courseScoreService;


    @GetMapping("/list")
    public R<List<Teacher>> findALL() {
        List<Teacher> teachers = teacherService.getAll();
        return RUtil.success(teachers);
    }

    @GetMapping("{id}")
    public R<Teacher> findById(@PathVariable int id) {

        Teacher teacher = teacherService.findById(id);
        return RUtil.success(teacher);
    }

    @GetMapping("/getByUserId")
    public R getByUserId(@RequestParam Integer userId) {
        Teacher teacher = teacherRepository.findByUserId(userId);
        Integer teacherId = teacher.getTeacherId();
        if (teacherId == null) {
            return RUtil.fail("未找到教师信息");
        }
        return RUtil.success(teacherId);
    }

    @PostMapping("/add")
    public R<Teacher> add(@RequestBody Teacher teacher) {
        return RUtil.success(teacherService.add(teacher));
    }

    @PutMapping("/update")
    public R<Teacher> update(@RequestBody Teacher teacher) {
        return RUtil.success(teacherService.update(teacher));
    }

//    @DeleteMapping("/delete/{id}")
//    public R delete(@PathVariable Integer id) {
//        studentService.delete(id);
//        return RUtil.success();
//    }

    //更改删除操作的连接
    @DeleteMapping("/deletebatch")
    public R delete(@RequestBody Iterable<Integer> ids) {
        teacherService.deletebatch(ids);
        return RUtil.success();
    }

//    @GetMapping("/validateUser")
//    public R validateUsernameAndPassword(String username, String password, HttpServletRequest request) throws Exception {
//        User user = studentService.validateUsernameAndPassword(username, password);
//
//        request.getSession().setAttribute("userInfo", user);
//        return RUtil.success();
//    }

    //    @PostMapping("/getbypage")
//    public R<Page<Teacher>> getByPage(@RequestBody QueryObj<Teacher> qObj) {
//        Sort sort = Sort.by(Sort.Direction.DESC, "id");
//        Integer pageIndex = 0;
//        Integer pageSize = 10;
//
//        if (qObj == null) {
//            Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
//            Page<Teacher> teachers = teacherService.getAll(pageable);
//            return RUtil.success(teachers.getContent(), teachers.getTotalElements());
//        } else {
//            pageIndex = qObj.getPage() - 1;
//            pageSize = qObj.getLimit();
//
//            if (qObj.getData() instanceof Teacher) {
//                Teacher teacher = (Teacher) qObj.getData();
//                Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
//
//                ExampleMatcher matcher = ExampleMatcher.matching()
//                        .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
//                        .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //添加一个姓名模糊匹配
//                        .withIgnoreNullValues();
//
//                Example<Teacher> example = Example.of(teacher, matcher);
//                Page<Teacher> teacherPage = teacherService.getAll(example, pageable);
//                return RUtil.success(teacherPage.getContent(), teacherPage.getTotalElements());
//            } else {
//                throw new RException(REnum.QUERY_ERR);
//            }
//        }
//
//
//    }
    @PostMapping("/getbypage")
    public R<Page<CourseScore>> getByPage(@RequestBody QueryObj<CourseScore> qObj) {
        Sort sort = Sort.by(Sort.Direction.DESC, "courseId");
        Integer pageIndex = 0;
        Integer pageSize = 10;

        log.info("接收到的参数: {}", qObj);
        if (qObj == null) {
            return RUtil.error(REnum.PARAM_ERROR); // 参数错误，返回错误响应
        } else {
            pageIndex = qObj.getPage() - 1;
            pageSize = qObj.getLimit();
            Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);

            // 获取studentId，若为null则返回错误
            Integer teacherId = null;
            if (qObj.getData() != null && qObj.getData().getTeacher() != null) {
                teacherId = qObj.getData().getTeacher().getTeacherId();
                System.out.println("提取的学生ID: " + teacherId);
            }

            if (teacherId == null || teacherId <= 0) {
                return RUtil.error(REnum.STUDENT_ID_REQUIRED); // 学生ID不能为空或无效
            }

            // 验证学生ID是否存在
            Teacher teacher = teacherService.getById(teacherId);
            if (teacher == null) {
                return RUtil.error(REnum.STUDENT_NOT_FOUND); // 学生不存在
            }

            Page<CourseScore> page = courseScoreService.findByTeacherTeaId(teacherId, pageable);
            return RUtil.success(page.getContent(), page.getTotalElements());
        }
    }

    @PutMapping("/updateScore")
    public R updateScore(@RequestBody Map<String, Object> params) {
        try {
            Integer id = (Integer) params.get("id");
            String score = (String) params.get("score");

            if (id == null || score == null) {
                return RUtil.error(REnum.PARAM_ERROR);
            }

            courseScoreService.updateScore(id, score);
            return RUtil.success();
        } catch (Exception e) {
            log.error("更新成绩失败", e);
            return RUtil.error(REnum.SERVER_ERR);
        }
    }


}